#include <stdio.h>
#include <stdlib.h>
#include "auth.h"
void GetAuthIdentifier(char *authIdentifier, size_t *authIdentifierLength)
{
    int rst = WD_GetAuthIdentifier(authIdentifier, authIdentifierLength);
	if(rst == WD_SUCESS)
	{
		cli_app_log(CLI_LOG_NOTICE,
				"GetAuthIdentifier OK!  authIdentifierLength:%d\n", *(int*)authIdentifierLength);
	}
    else
	{
		cli_app_log(CLI_LOG_CRITICAL,
						"GetAuthIdentifier Faild! rst:%d\n", rst);
	}
}




I32 auth_init(char *regInfo, int auth_len, char *file, char *addr, I32 port, char *authIdentifier, size_t *authIdentifierLength)
{
    int rst = WD_AuthSDKInit();
	if (rst == WD_SUCESS)
	{
		cli_app_log(CLI_LOG_NOTICE,
						"SDK Initial success!\n");
	} 
    else
	{
		cli_app_log(CLI_LOG_CRITICAL,
						"SDK Initial faild! SDK_rst:%d\n", rst);
		return 1;
	}
	cli_app_log(CLI_LOG_INFO,
						"%s\n",regInfo);
	FILE* cerFile = fopen(file, "r");
	if (cerFile == NULL) 
    {
		cli_app_log(CLI_LOG_CRITICAL,
						"Read certificate file faild!\n");
		return 1;
	}
	char cerBuffer[1024] = {0};
	size_t cerLen = fread(cerBuffer, 1, 1024, cerFile);
	cli_app_log(CLI_LOG_INFO,
						"%s\n Certificate - length:%d\n", cerBuffer, (int)cerLen);
	fclose(cerFile);
	int cerFormat = WD_CheckCertificateFormat(cerBuffer, cerLen);
	if (cerFormat != WD_SUCESS) 
	{
	
		cli_app_log(CLI_LOG_CRITICAL,
						"certificate file format err!");
		return 1;
	}
	rst = WD_StartAuth(addr, 18, port, regInfo, auth_len, (const char*)cerBuffer, cerLen, 1);
	if (rst == WD_SUCESS) 
	{
		cli_app_log(CLI_LOG_NOTICE,
						"Auth OK!\n");
		//get authidentifier
		GetAuthIdentifier(authIdentifier, authIdentifierLength);

	} else 
	{
		cli_app_log(CLI_LOG_CRITICAL,
					"Auth Faild! Code:%d\n", rst);
	}
	return rst;

}
